import express from 'express';
import path from 'path';
import { prisma } from './service/mysql.js';
import { getDirName } from './tools/index.js';
import fundsRouter from './routes/funds.js';
import scheduleTasksRouter from './routes/schedule-tasks.js';
import statisticsRouter from './routes/statistics.js';
import fundsOptionsRouter from './routes/funds-options.js';
import userRouter from './routes/user.js';
import { initCronTask } from './service/cron.js';
import { createRobot } from './wechat/index.js';

// 创建微信机器人
const wechatRobot = await createRobot();
initCronTask(wechatRobot);

const app = express();
const __dirname = getDirName(import.meta.url);
const staticDir = path.join(path.dirname(__dirname), 'public');

app.locals.wechatRobot = wechatRobot;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(staticDir));

app.use('/api/login', async (req, res) => {
  const { password } = req.body;
  const userCnt = await prisma.t_accounts.count({
    where: {
      account_certificate: password
    }
  });
  if (userCnt < 1) {
    res.json({
      success: false,
      message: '凭证码错误，请联系管理员获取。',
      data: null
    });
  }
  res.json({
    success: true,
    message: '',
    data: null
  });
});

app.all('/api/*', async function (req, res, next) {
  const token = req.header('Token');
  const accountUser = await prisma.t_accounts.findFirst({
    where: {
      account_certificate: token
    }
  });
  if (!accountUser) {
    return res.json({
      success: false,
      code: 401,
      message: '无权访问',
      data: null
    });
  }
  // 设置当前账本信息

  req.context = {
    accountNo: accountUser.account_no
  };

  next();
});

app.use('/api', [fundsRouter, scheduleTasksRouter, statisticsRouter, fundsOptionsRouter, userRouter]);

app.get('*', (req, res) => {
  // 如果不是API路由，总是发回主index.html，让前端框架来处理路由。
  res.sendFile(path.join(staticDir, 'index.html'));
});

// error handler
app.use(function (err, req, res, next) {
  console.error('handle error...', err.stack);
  res.json({
    success: false,
    message: '服务繁忙，请稍后再试',
    data: null
  });
});

export default app;
